const app = getApp()
const {throttle} = require('../../../utils/throttle')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    FjLoginLog: '',
    // 省
    areaList: [],
    provinceCurrentIdx: 0,
    cityList: [],
    cityCurrentIdx: 0,
    townList: [],
  },

  // 清除
  cancel(){
    const {areaList, cityList, townList} = this.data
    areaList.map(one => {
      one.is_choice = 0
      one.signName = ''
      if(!one.children || !one.children.length) return

      one.children.map(two => {
        two.is_choice = 0
        two.signName = ''
        if(!two.children || !two.children.length) return

        two.children.map(three => {
          three.is_choice = 0
        })
      })
    })

    cityList.map(item=> {item.is_choice = 0; item.signName = ''})
    townList.map(item=> item.is_choice = 0)

    this.setData({
      areaList,
      cityList,
      townList
    })
  },
  throttle(){},
  sure(){
   this.throttle()
  },
  save(){
    const selectArea = this.data.areaList.filter(item => item.is_choice)
    if(!selectArea.length){
      return wx.showToast({
        title: '请选择区域',
        icon: 'none'
      })
    }
    const params =this.getParams(selectArea)
    const _this = this
    wx.request({
      url: app.data.api_url2+"v/vip_zone_set/",
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      data: {
        'user_id': _this.data.FjLoginLog.UID,
        'choice_json': params
      },
      method: 'POST',
      success: function(res) {
        if (res.statusCode == 200) {
          if(res.data.code == 200){
            wx.navigateBack()
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
        } else {
          wx.showToast({
            title: '操作失败',
            icon: 'none'
          })
        }
      }
    })
  },
  getParams(arr){
    const params = []
    arr.map(one => {
      // 若省无子集
      if(!one.children || !one.children.length){
        return params.push({one: one.code})
      }
      
      const twoAreas = one.children.filter(item => item.is_choice)

      const isAll = twoAreas.every(two => (two.signName+'').localeCompare('全') === 0)
      if((twoAreas.length === one.children.length) && isAll){
        return params.push({one: one.code})
      }

      twoAreas.map(two => {
        // 选中的市若无子集
        if(!two.children || !two.children.length){
          return params.push({one: one.code, two: two.code})
        }

        const threeAreas = two.children.filter(item => item.is_choice)
        if(threeAreas.length === two.children.length){
          return params.push({one: one.code, two: two.code})
        }
        // 区县集
        threeAreas.map(three => {
          params.push({one: one.code, two: two.code, three: three.code})
        })
      })
      
    })
    return JSON.stringify(params)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.throttle = throttle(this.save, 2000)
  },
  onShow() {
    this.setData({
      FjLoginLog : wx.getStorageSync('FjLoginLog')
    })
    this.getArea()
  },
  // 获取区域
  getArea(){
    const _this = this
    wx.request({
      url: app.data.api_url2+"v/sign_zone_select/",
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      data: {
        'user_id': _this.data.FjLoginLog.UID,
      },
      method: 'POST',
      success: function(res) {
        if (res.statusCode == 200) {
          if(res.data.code == 200){
            const datalist = res.data.data.map(item => {
              item.signName = ''
              return item
            })
            // 回显区域
            _this.valuation(datalist)
            _this.initShow(datalist)
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
        }
      }
    })
  },
  // 区域回显
  valuation(datalist){
    const selectList = datalist.filter(item=> item.is_choice)
    if(!selectList.length){
      return
    }
    selectList.map(one=>{
      if(!one.children || !one.children.length){
        one.signName = '全'
        return
      }
      const selectTwo = one.children.filter(two => two.is_choice)
      one.signName = selectTwo.length === one.children.length
        ? '全'
        : selectTwo.length

      one.children.map(two => {
        if(!two.children || !two.children.length){
          two.signName = '全'
          return
        }
        const selectThree = two.children.filter(three => three.is_choice)
        two.signName = selectThree.length === two.children.length
        ? '全'
        : selectThree.length
      })
    })
  },
  // 定位点击省市区并初始加载
  initShow(datalist){
    const provinceCurrentIdx = datalist.findIndex(item => item.is_choice)
    if(provinceCurrentIdx === -1){
      return this.setData({
        areaList: datalist
      })
    }
    if(!datalist[provinceCurrentIdx].children && !datalist[provinceCurrentIdx].children.length){
      return this.setData({
        areaList: datalist,
        provinceCurrentIdx
      })
    }

    const cityList = datalist[provinceCurrentIdx].children
    const cityCurrentIdx = cityList.findIndex(item => item.is_choice)
    if(cityCurrentIdx === -1){
      return this.setData({
        areaList: datalist,
        provinceCurrentIdx,
        cityList
      })
    }
    if(!cityList[cityCurrentIdx].children && !cityList[cityCurrentIdx].children.length){
      return this.setData({
        areaList: datalist,
        provinceCurrentIdx,
        cityList,
        cityCurrentIdx
      })
    }
    
    const townList = cityList[cityCurrentIdx].children
    this.setData({
      areaList: datalist,
      provinceCurrentIdx,
      cityList,
      cityCurrentIdx,
      townList
    })
  },
  // 点击省
  provinceClick(e){
    const { idx } = e.target.dataset
    const { areaList, provinceCurrentIdx } = this.data
    // 切换省，则默认选中
    if(provinceCurrentIdx == idx){
      areaList[idx].is_choice = areaList[idx].is_choice ? 0  : 1
      this.setChioce(areaList[idx])
      this.setSign(areaList[idx])
    } else {
      if(!areaList[idx].is_choice){
        areaList[idx].is_choice = 1
        this.setChioce(areaList[idx])
        this.setSign(areaList[idx])
      }
    }
    
    this.setData({
      areaList: areaList,
      provinceCurrentIdx: idx,
      cityList: [],
      cityCurrentIdx: 0,
      townList: [],
    })
    this.getChildArea(1)
    this.getChildArea(2)
  },
  
  // 点击市
  cityClick(e){
    const { idx } = e.target.dataset
    const { areaList, cityList, cityCurrentIdx } = this.data
    if(cityCurrentIdx == idx){
      cityList[idx].is_choice = cityList[idx].is_choice ? 0  : 1
      this.setChioce(cityList[idx])
      this.setParentChioce(cityList[idx])
      this.setSign(cityList[idx])
    } else {
      if(!cityList[idx].is_choice){
        cityList[idx].is_choice = 1
        this.setChioce(cityList[idx])
        this.setParentChioce(cityList[idx])
        this.setSign(cityList[idx])
      }
    }
    this.setData({
      areaList: areaList,
      cityList: cityList,
      cityCurrentIdx: idx,
      townList: [],
    })
    this.getChildArea(2)
  }, 

  // 找下一级的区域
  getChildArea(level){
    const { areaList, provinceCurrentIdx, cityList, cityCurrentIdx } = this.data
   
    switch (level){
      case 1:
        if(areaList[provinceCurrentIdx].children){
          this.setData({
            cityList: areaList[provinceCurrentIdx].children
          })
        }
      break;
      case 2:
        if(cityList[cityCurrentIdx] && cityList[cityCurrentIdx].children){
          this.setData({
            townList: cityList[cityCurrentIdx].children
          })
        }
      break;
    }
  },
  
  // 切换--当前项子项选中与取消选中
  setChioce(data){
    if(!data.children) return
    data.children.forEach(item => {
      item.is_choice = data.is_choice
      this.setChioce(item)
    })
  },

  // 设置父元素选中
  setParentChioce(){
    let { areaList, provinceCurrentIdx, cityList } = this.data
    areaList[provinceCurrentIdx].is_choice = 1

    // 设置市选中状态及角标
    const len = cityList.filter(item => item.is_choice).length
    if(!len){
      areaList[provinceCurrentIdx].is_choice = 0
    }
  },

  // 设置元素角标
  setSign(data){
    let { areaList, provinceCurrentIdx, cityList } = this.data
    // 设置当前元素角标提示
    if(data.is_choice){
      data.signName = '全'
    } else {
      data.signName = ''
    }
    // 关联其父角标提示
    if(data.parent_id){
      const len = areaList[provinceCurrentIdx].children.filter(item => item.is_choice).length
      if(cityList.length === len){
        areaList[provinceCurrentIdx].signName = '全'
      } else {
        areaList[provinceCurrentIdx].signName = len
      }
    }

    // 关联其子角标提示
    if(data.children){
      data.children.forEach(item => {
        item.signName = data.is_choice ? '全' : ''
      })
    }
  },

  // 点击区县
  townClick(e){
    let { areaList, provinceCurrentIdx, cityList, cityCurrentIdx, townList } = this.data
    const { idx } = e.target.dataset
    townList[idx].is_choice = townList[idx].is_choice ? 0 : 1
    cityList[cityCurrentIdx].is_choice = 1
    areaList[provinceCurrentIdx].is_choice = 1

    // 设置市选中状态及角标
    const len = townList.filter(item => item.is_choice).length
    if(!len){
      cityList[cityCurrentIdx].is_choice = 0
    }
    if(cityList[cityCurrentIdx].children.length === len){
      cityList[cityCurrentIdx].signName = '全'
    } else {
      cityList[cityCurrentIdx].signName = len
    }

    // 设置省选中状态及角标
    const lenP = areaList[provinceCurrentIdx].children.filter(item => item.is_choice).length
    if(!lenP){
      areaList[provinceCurrentIdx].is_choice = 0
    }
    if(cityList.length === lenP){
      areaList[provinceCurrentIdx].signName = '全'
    } else {
      areaList[provinceCurrentIdx].signName = lenP
    }

    this.setData({
      areaList: areaList,
      cityList: cityList,
      townList: townList
    })
  },

})